package com.kfm.spring.dao.impl;

import com.kfm.spring.dao.IAccountDao;
import com.kfm.spring.model.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

//@Component("accountDao")
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

//    @Autowired
//    @Qualifier("runner")
//    @Resource(name = "runner", type = QueryRunner.class)

    @Autowired
    private QueryRunner queryRunner;

    private Connection conn;

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public Connection getConn(){
        try {
            return queryRunner.getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


//    public void setQueryRunner( QueryRunner queryRunner) {
//        this.queryRunner = queryRunner;
//    }

//    public AccountDaoImpl(QueryRunner queryRunner){
//        this.queryRunner = queryRunner;
//    }

    @Override
    public int save(Account account) {
        String sql = "insert into account(uid, money) values(?, ?)";
        try {
            return queryRunner.update(conn, sql, account.getUid(), account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Account account) {

        return 0;
    }

    @Override
    public int delete(int id) {
        String sql = "delete from account where id = ?";
        try {
            return queryRunner.update(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findById(int id) {
        String sql = "select * from account where id = ?";
        try {
            return queryRunner.query(sql, new BeanHandler<>(Account.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Account> findAll() {
        String sql = "select * from account";
        List<Account> query = null;
        try {
            query = queryRunner.query(sql, new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;
    }

}
